using System.Buffers;
using System.Runtime.InteropServices;
using SuperSocketProxy.Commands;

namespace SuperSocketProxy;

public sealed class SocketProxyDataPacket : SocketProxyPacket
{
    public SocketProxyDataPacket()
    {
        Key = Command.ForwardData;
    }

    public List<ArraySegment<byte>> Body { get; private set; }

    public override SocketProxyPacket Decode(ref SequenceReader<byte> reader)
    {
        try
        {
            Body = new List<ArraySegment<byte>>();
            
            foreach (var memory in reader.Sequence)
            {
                if (!MemoryMarshal.TryGetArray(memory, out var segment))
                    throw new InvalidOperationException("Buffer backed by array was expected");
                
                Body.Add(segment);
            }
        }
        finally
        {
            reader.AdvanceToEnd();
        }

        return this;
    }
}